import WS from '@/libs/ws.js'
import { reactive } from 'vue'
import axios from 'axios'
import { extractUrls, extractMarkdown } from '../../utils/util'
import { dayjs } from 'element-plus'

import { useScroll } from './utils/scroll'
import MessageQueue from './utils/message-queue'
import { prompts } from './dict'
// import { encode, decode } from 'js-base64'

const WS_URL = localStorage.ws || import.meta.env.VITE_APP_WS || `${location.origin}/v1/soc/`

const useMessage = options => {
  const chatTimes = {}
  const state = reactive({
    messages: [],

    loading: false, // 思考中

    taskId: null, // 当前任务ID
    tasks: {}, // 任务
    taskMessages: {}, // 任务消息

    dialog: {
      input: { show: false },
      preview: { show: true },
    },

    showWelcome: true, // 是否显示欢迎语

    isQueryDevice: false, // 是否查询设备
  })

  let ws

  const send = async msg => {
    console.log('msg', msg)

    if (!ws) {
      await new Promise((resolve, reject) => {
        ws = new WS({
          url: WS_URL,
          onConnect: () => {
            options.onConnect && options.onConnect()
            resolve()
          },
          onMessage: value => {
            onMessage(value)
          },
        })
      })
    }

    ws.send(msg)
  }

  const input = async msg => {
    console.log('input')

    state.loading = true
    if (state.showWelcome) state.showWelcome = false

    if (options.chatState.sendbox.isQueryDevice) {
      send('@search_cwpp: ' + msg)
    } else {
      send('@input: ' + msg)
    }

    state.messages.push({
      role: 'user',
      type: 'text',
      content: prompts[msg] || msg,
    })
  }

  function onMessage(item) {
    if (typeof item == 'string') {
      try {
        item = JSON.parse(item)
      } catch (e) {
        item = {
          role: 'system',
          text: item,
        }
      }
    }

    try {
      const { texttype, role, text, id } = item

      // 会话消息
      if (role == 'ws_session') {
        options.onSession && options.onSession(item)
        return
      } else if (role == 'ws_session_details') {
        state.history = true
        state.showWelcome = false

        item.text.map(item => {
          if (item.flag == 'ask') {
            state.messages.push({
              role: 'user',
              type: 'text',
              content: prompts[item.text] || item.text,
            })
          } else {
            onMessage(item)
          }
        })
        return
      }

      // 文档click消息
      if (id && id == state.preview?.docId) {
        state.dialog.preview.show = true
        state.dialog.preview.data = {
          type: state.preview.type,
          content: item.content,
        }

        return messageQueue.next()
      }

      const taskIndex = item.taskindex
      // const taskId = item.taskid ? item.taskid.replace('@taskid:', '') + `-${taskIndex}` : ''
      let taskId

      if (role == 'agent_steps') {
        taskId = item.taskid ? item.taskid.replace('@taskid:', '') + `-${taskIndex}` : ''

        console.log('taskId', taskId)

        state.taskId = taskId
      }

      // 预览消息
      if (['tool_response', 'tool_output', 'ai_output', 'ai_thought'].includes(role)) {
        taskId = item.taskid ? item.taskid.replace('@taskid:', '') + `-${taskIndex}` : ''

        if (!state.taskMessages[taskId]) state.taskMessages[taskId] = []

        // 网页报告
        if (item.role == 'tool_response' && item.text.indexOf('已成功生成网页') != -1) {
          item.texttype = 'web'
          item.text = item.text.split('已成功生成网页:').pop()

          console.log('item.content', item.content)

          state.taskMessages[taskId].push(item)
        } else {
          state.taskMessages[taskId].push(item)
        }

        return
      }

      if (text == '@complate_task') {
        state.loading = false
        // messageQueue.next()
        return
      } else if (text == '@start_task') {
        //  messageQueue.next()
        return
      }

      const result = {
        role: 'system',
        inputType: role,
        // data: item,
        time: dayjs(item.timestamp * 1000).format('HH:mm'),
        taskId,
        rawTaskId: item.taskid?.replace('@taskid:', ''),
      }

      //       {
      //   text: '@taskid:8d17a752-1678-405d-85ad-909ed7cfc0dc\n- [x] 查询主机类型分布统计数据\n- [ ] 查询容器状态分布统计数据\n- [ ] 查询应用资产分布统计数据\n- [ ] 查询软件安装包分布统计数据',
      //   role: 'agent_steps',
      //   texttype: 'markdown',
      //   taskid: '@taskid:8d17a752-1678-405d-85ad-909ed7cfc0dc',
      //   taskindex: 1,
      //   timestamp: 1747908702.9422812,
      // },

      if (['doc_id', 'html_id'].includes(item.role)) {
        result.type = { html_id: 'html', doc_id: 'doc' }[item.role]

        try {
          result.content = JSON.parse(item.text.replaceAll(`'`, `"`))
        } catch (e) {
          result.content = [item.text]
          console.warn('doc_id或html_id解析失败', item.text)
        }
      } else if (item.texttype == 'markdown') {
        result.type = 'markdown'
        // result.content = extractMarkdown(item.text)
        result.content = item.text

        // 判断内容是否可以进行折叠
        // const texts = result.content.split('\n')

        //       if (texts.length && texts[0].indexOf('**') != -1) {
        //         result.content = `
        // <details> <summary>${title}</summary>
        // ${texts.join('<br>')}
        // </details>
        //         `
        //       }
      } else if (item.texttype == 'string') {
        result.type = 'txt'
        result.content = item.text
      }

      // 后期优化
      if (role == 'agent_steps') {
        const ary = text
          .split('\n')
          .slice(1)
          .map(val => {
            const item = {}

            if (val.indexOf('[x]') != -1) {
              item.title = val.replace('- [x] ', '')
              item.isSelect = true
            } else {
              item.title = val.replace('- [ ] ', '')
              item.isSelect = false
            }

            return item
          })

        console.log('ary', ary)

        result.type = 'agent_steps'
        result.content = ary
      }

      const addTime = () => {
        if (!chatTimes[result.time]) {
          chatTimes[result.time] = true
          // 丢队列
          // messageQueue.push({
          //   role: 'system',
          //   type: 'time',
          //   content: result.time,
          // })

          // 直接渲染
          state.messages.push({
            role: 'system',
            type: 'time',
            content: result.time,
          })
        }
      }

      if (result.rawTaskId) {
        // 判断任务是否相同
        const index = state.messages.findIndex(item => item.rawTaskId == result.rawTaskId)
        if (index != -1) {
          state.messages[index] = result
        } else {
          addTime()
          state.messages.push(result)
        }
      } else {
        addTime()
        state.messages.push(result) // 直接渲染
        // messageQueue.push(result) // 往队列里面丢
      }

      if (role == 'user_input') {
        state.loading = false // 思考结束
        // clearInterval(timeClock)
      }
    } catch (e) {
      console.error(e)
    }
  }

  return {
    ws,
    send,
    input,
    state,
  }
}

export const useChatStore = () => {
  const scrollContainer = ref(null)
  const previewScrollRef = ref(null) // 预览滚动元素

  const state = reactive({
    chats: [],
    chatId: null,

    // 发送框
    sendbox: { isQueryDevice: false },

    dialog: {
      input: { show: false, data: null },
      preview: { show: false, data: null },
    },

    preview: null, // 消息回调
  })

  const chat = computed(() => state.chats.find(item => item.chatId == state.chatId))
  const chatItemStore = computed(() => chat.value?.store)
  const messages = computed(() => chatItemStore.value?.state.messages)

  const chatListWs = new WS({
    url: WS_URL,
    onConnect: () => {
      chatListWs.send('')
    },
    onMessage: value => {
      const data = JSON.parse(value)
      if (data.role == 'ws_session') {
        data.text.forEach(item => {
          const store = useMessage({
            chatState: state,
          })

          state.chats.push({
            title: JSON.parse(item.text)[0],
            chatId: item.wsclientid,
            store,
            type: 'history',
          })
        })
        chatListWs.close()
      }
    },
  })

  // 创建一个会话
  const createChat = options => {
    const chatId = new Date().getTime()
    const store = useMessage({
      chatState: state,
      ...options,
    })

    state.chats.push({
      chatId,
      store,
    })
    state.chatId = chatId
  }

  const handleInput = text => {
    if (!chat.value) createChat()

    chat.value.store.input(text)
  }

  return {
    state,

    chat,
    chatItemStore,
    messages,

    createChat,
    handleInput,

    scrollContainer,
    previewScrollRef,
  }
}
